<template>
    <div class="app-container">
        <el-row gutter="20" class="marginTop10">
            <el-col :span="12">
                <el-card>
                    <el-row align="middle">
                        <el-col :span="12"><h4 v-if="rowData">{{ rowData.companyName }}</h4></el-col>
                        <el-col :span="12" class="text-right"><h4>提箱城市：{{ rowData.carryCityName }}/{{ rowData.carryCountryName }}</h4></el-col>
                    </el-row>
                    <el-divider border-style="dashed" style="margin-top: 0px;"/>
                    <el-row>
                        <el-col :span="24">
                            <el-table ref="myTable" :data="tableInfo" style="width: 100%;height: 190px;" :row-class-name="tableRowClassName"> 
                                <el-table-column prop="returnCity" label="还箱城市" align="center">
                                    <template #default="scope">
                                        <el-select v-model="scope.row.returnCityId" placeholder="请选择城市" style="width: 100%" @change="changeCity">
                                            <el-option v-for="(item,index) in scope.row.returnCity" :key="index" :label="item.returnCityName" :value="item.returnCityId"></el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="unitPrice" label="单价" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.unitPrice" placeholder="请输入单价" :formatter="formatterNumber" :parser="formatterNumber" class="el-price" style="width: 100%;">
                                            <template #prefix>
                                                <el-select v-model="scope.row.currency" placeholder="Select" style="width: 60px">
                                                    <el-option label="＄" value="USD"></el-option>
                                                    <el-option label="￥" value="CNY"></el-option>
                                                </el-select>
                                            </template>
                                        </el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="boxQuantity" label="下单量" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.boxQuantity" placeholder="请输入箱量" oninput="value=value.replace(/^(0+)|[^\d]+/g,'')" class="input-width"/>
                                    </template>
                                </el-table-column>
                                
                                <el-table-column prop="city" align="center" width="50">
                                    <template  #default="scope"><el-icon size="20" class="cursor" @click="handleDelete1(scope.$index)"><Remove /></el-icon></template>
                                </el-table-column>
                            </el-table>
                        </el-col>
                        <el-col :span="24" class="marginTop5">
                            <el-row align="middle">
                                <el-col :span="12">
                                    <el-icon :size="25" color="#2158F3" class="cursor"  @click="handleAdd1"><CirclePlus /></el-icon>
                                </el-col>
                                <el-col :span="12" class="text-right">
                                    <span class="_asterisk">结算流向：</span>
                                    <el-radio-group v-model="agentDirection">
                                        <el-radio value="-1" size="large">应付</el-radio>
                                        <el-radio value="1" size="large">应收</el-radio>
                                    </el-radio-group>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card>
                    <el-row class="marginTop10">
                        <el-col :span="3" class="text-right">总箱量：</el-col><el-col :span="4">{{totalBoxNum}}</el-col>
                        <el-col :span="8">箱型：{{basicConfig.boxTypeInfo1[param.boxType]}}</el-col>
                        <el-col :span="8">箱况：{{basicConfig.boxConditionInfo2[param.boxCondition]}}</el-col>
                    </el-row>
                    <el-row class="marginTop25">
                        <el-col :span="3" class="text-right">超期费：</el-col><el-col :span="20">超期1天，{{basicConfig.currency2[rowData.overdueFeeCurrency]}}{{rowData.overdueFeeDay}}/箱/天；超期{{rowData.lossDay}}天后仍未还箱，视为灭失，灭失费为{{basicConfig.currency2[rowData.overdueFeeCurrency]}}{{rowData.lossFee}}</el-col>
                    </el-row>
                    <el-row class="marginTop25">
                        <el-col :span="3" class="text-right">货品名称：</el-col><el-col :span="20">{{rowData.cargoName || '暂无货品名称'}}</el-col>
                    </el-row>
                    <el-row class="marginTop25">
                        <el-col :span="3" class="text-right">联系人：</el-col><el-col :span="4">{{rowData.publisherName}}</el-col> 
                        <el-col :span="8">联系电话：+{{rowData.publisherAreaCode}} {{rowData.publisherTel}} </el-col>
                        <el-col :span="8">修箱费：还箱时，实报实销</el-col>
                    </el-row>
                    <el-row class="marginTop25">
                        <el-col :span="3" class="text-right">留言：</el-col>
                        <el-col :span="20">
                            <el-input v-model="param.leaveMsg" style="width: 100%" :rows="5" show-word-limit maxlength="500" type="textarea" placeholder="请输入留言信息"/>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
        </el-row>
        <el-card class="marginTop20 marginBottom20">
            <span class="_before">订单信息</span>
            <el-row class="marginTop20" align="middle">
                <el-col :offset="1" :span="2" class="text-right"><span class="_asterisk">预计提箱日期： </span></el-col>
                <el-col :span="6">
                    <el-date-picker v-model="param.planPickupDate" type="date" :disabled-date="disabledDate" placeholder="提箱日期" />
                </el-col>
                <el-col :span="2" class="text-right"><span class="_asterisk">支付方式： </span></el-col>
                <el-col :span="6">
                    <el-select v-model="param.paymentMethod" style="width:200px">
                        <el-option label="对公转账" value="5"></el-option>
                        <el-option label="在线支付" value="10"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="2" class="text-right"><span class="_asterisk">结算账期： </span></el-col>
                <el-col :span="5"> 
                    <el-input v-model="param.period" placeholder="请输入天数" @input="handlePeriodInput" style="width:200px">
                        <template #append>天</template>
                    </el-input>
                </el-col>

                <el-col :offset="1" :span="2" class="text-right marginTop20"><span class="_asterisk">箱使期： </span></el-col>
                <el-col :span="6" class="marginTop20"> 
                    <el-input v-model="rowData.boxUsagePeriod" placeholder="请输入天数" style="width:200px">
                        <template #append>天</template>
                    </el-input>
                </el-col>
            </el-row>
            <el-divider  border-style="dashed"/>
            <el-row class="marginBottom20" align="middle">
                <el-col :offset="1" :span="2" class="text-right"><span class="_asterisk">经办人：</span></el-col>
                <el-col :span="6">{{nickName}}</el-col>
            </el-row>

            <el-row v-for="(item,index) in allocation" :key="index" align="middle" class="marginBottom10">
                <el-col :offset="1" :span="2" class="text-right"><span class="_asterisk">业务员：</span></el-col> 
                <el-col :span="6">
                    <el-select v-model="item.businessUserId" filterable style="width: 50%;">
                        <el-option v-for="(user, index) in param.userSimpleList" :key="index" :label="user.nickname" :value="user.userId" />
                    </el-select>
                </el-col>
                <el-col :span="2" class="text-right"><span class="_asterisk">操作员：</span></el-col>
                <el-col :span="6">
                    <el-select v-model="item.operateUserId" filterable style="width: 50%;">
                        <el-option v-for="(user, index) in param.userSimpleList" :key="index" :label="user.nickname" :value="user.userId" />
                    </el-select>
                </el-col>
                <el-col :span="2" class="text-right"><span class="_asterisk">业务编号：</span></el-col>
                <el-col :span="3">
                    <el-input v-model="item.businessNo" style="width: 100%" placeholder="请输入业务编号" maxlength="100"/>
                </el-col>
                <el-col :span="1" v-if="allocation.length >= 2" class="text-center"><el-icon :size="20" color="#2158F3" class="cursor"  @click="handleDelete(index)"><Remove /></el-icon></el-col> 
            </el-row>
            <el-row class="marginTop20" align="middle">
                <el-col :offset="2" :span="10" v-if="allocation.length <= 4"> <el-icon :size="25" color="#2158F3" class="cursor"  @click="handleAdd"><CirclePlus /></el-icon></el-col>
            </el-row>
            <!-- <el-divider  border-style="dashed"/>
            <span>留言</span>
            <el-input v-model.trim="param.leaveMsg" type="textarea" clearable show-word-limit maxlength="1000" rows="5" placeholder="请输入留言信息" class="marginTop10"/> -->
        </el-card>
        <el-affix position="bottom">
            <el-card>
                <el-row align="middle" justify="center">
                    <el-col :span="9"> 
                        <el-checkbox v-model="radioVal" size="large" />我已阅读<a style="color: #2020eb;" href="#">《集装箱租赁业务规则》</a><a style="color: #2020eb;" href="#">《用户服务协议和管理规则》</a>并同意全部条款
                    </el-col>
                    <el-col :span="2"><el-button type="primary" @click="handleSubmit">提交订单</el-button></el-col>
                </el-row>
            </el-card>   
        </el-affix>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, computed, nextTick} from 'vue'
import  Carousel from '@/components/carousel'
// import { getBoxInfo } from '@/api/boxRent'
import { getBoxInfo } from '@/api/boxRent/indexNew'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import Cookies from 'js-cookie'
import { userSimpleList } from '@/api/user/index'
import  basicConfig from '@/constant/containerInfo';
import { agentAddOrder } from '@/api/orderManage'
const route = useRoute()
const router = useRouter()
const radioVal = ref(false) // 是否勾选业务条款
const rowData = ref({ // 集装箱基本信息
    id:'',
    companyName:'',
    carryCityName:'',
    returnCityName:'',
    carryCountryName:'',
    returnCountryName:'',
    boxUsagePeriod:'',
    areaCode:'86',
    publisherName:'',
    publisherTel:''
}) 
const allocation = ref([
    {
        businessUserId: '',           // 业务员id
        businessUserName: "",  // 业务员名称
        operateUserId: '' as string | number, // 操作员id
        operateUserName: "",   // 操作员名称
        businessNo: ""   // 业务编号
    }
])
interface UserSimple {
  userId: string | number
  nickname: string
}

const agentDirection = ref('-1') // 结算流向 -1：支出， 1-收入
const tableInfo = ref([
    {currency:"USD",unitPrice:"0",boxQuantity:0,cargoName:"",returnCityId:0,returnCity:[]} //默认数据
]) 
const tableInfoLength1 = ref(1)
const tableInfoLength2 = ref(1)
const repeatedSubscripts = ref(0)
const myTable = ref()
//添加提箱城市
const handleAdd1 = async() =>{
    if(repeatedSubscripts.value) return ElMessage.warning("还箱城市不能重复")
    const lastObject = {...tableInfo.value[tableInfo.value.length - 1]}
    if(tableInfo.value.length > 1){
        const lastSecondObject =  tableInfo.value[tableInfo.value.length - 2]
        if(lastSecondObject.returnCityId == lastObject.returnCityId){
            tableInfoLength1.value = tableInfo.value.length - 1 
            return ElMessage.warning("提箱城市不能重复")
        }
    }
    if(tableInfo.value.length> 9) return ElMessage.warning('最多添加10个还箱城市')
    tableInfo.value.push(lastObject)
    nextTick(() => {
        scrollToBottom();
    });

}

const changeCity = (cityId:number) => { 
    const duplicateInfo = findDuplicateIndexes(tableInfo.value, 'returnCityId') || [];
    if(Array.isArray(duplicateInfo) && duplicateInfo.length > 1){
        repeatedSubscripts.value = 1
        tableInfoLength1.value = duplicateInfo[0]
        tableInfoLength2.value = duplicateInfo[1]
    }else{
        repeatedSubscripts.value = 0
        tableInfoLength1.value = -1
        tableInfoLength2.value = -1
    }
}
const tableRowClassName = ({row,rowIndex}) => {
    if (rowIndex == tableInfoLength1.value || rowIndex == tableInfoLength2.value) {
        return 'warning-row'
    }
    return ''
}
// 删除提箱城市
const handleDelete1 = (index:number) =>{
    if(tableInfo.value.length < 2) return ElMessage.warning('最少需保留一个还箱城市')
    tableInfo.value.splice(index,1)
}

const totalBoxNum = computed(() => {
    let total = 0
    tableInfo.value.forEach(item => {
        total = total + Number(item.boxQuantity)
    })
    return total
})
const param = reactive({
    currency:'USD',
    unitPrice: 0,
    inventory: 1,
    planPickupDate:'',
    paymentMethod:'5',
    period:'20',
    businessNo:'',
    businessUserId:'5',
    operateUsers:'10',
    remark:'',
    boxType: route.query.boxType || '5',
    boxCondition: route.query.boxCondition || '5',
    total:'',
    userSimpleList:[] as UserSimple[],
    leaveMsg:''
})
const total = ref(0)
const  boxInfo = async()=> {
    if(!route.query.boxId) return ElMessage.warning('参数错误,请返回上一级并刷新页面')
    await getBoxInfo(route.query.boxId).then( res =>{ 
        if(res.code == '00000'){
            let _resData = res.data
            rowData.value = _resData
            param.planPickupDate = _resData.planPickupDate
            param.paymentMethod = _resData.paymentMethod || '5'
            param.period = _resData.period || '30'
            param.remark = _resData.remark
            agentDirection.value = String(_resData.direction * -1)
            // swiperData.list = _resData.mainFileList? JSON.parse(_resData?.mainFileList) : []
            // try{ 
            //     allocation.value = JSON.parse(_resData?.allocation) 
            // }catch(e){}
            // if(_resData?.releaseRentPriceList && route.query.boxType && route.query.boxCondition){
            //     _resData.releaseRentPriceList.forEach(item => { 
            //         if(route.query.boxType == item.boxType && route.query.boxCondition == item.boxCondition ){
            //             param.currency = item.currency
            //             param.unitPrice = item.unitPrice
            //             total.value = Number((item.unitPrice * param.inventory).toFixed(2))
            //         }
            //     })
            // }
            const data = {currency:"USD",unitPrice:"1",boxQuantity:0,cargoName:"哈哈哈",returnCityId:0,returnCity:[]}
            if(_resData?.priceList && route.query.boxType && route.query.boxCondition){
                tableInfo.value.splice(0, tableInfo.value.length)
                JSON.parse(_resData?.priceList).forEach(item => { 
                    if(route.query.boxType == item.boxType && route.query.boxCondition == item.boxCondition ){
                        data.currency = item.currency
                        data.unitPrice = item.unitPrice
                        data.cargoName = _resData.cargoName
                        
                        data.returnCityId = Number(route.query.returnCityId)
                        data.returnCity =   JSON.parse(_resData.returnCity)
                    }
                })
                tableInfo.value.push({...data})
            }
        }else{
            ElMessage.warning(res.msg)
        }
    })

}

const swiperData = reactive({
  list: [],
  config: {
    width:"100%",
  }
})

const nickName = computed(()=>{
  return JSON.parse(Cookies.get("User-Info"))?.nickname
})

onMounted(()=>{ 
    userSimpleList({}).then(res=>{ 
        if(res.code == '00000' && res.data.length > 0){
            param.userSimpleList = res.data
            localStorage.setItem('userSimpleList', JSON.stringify(res.data))

            allocation.value[0].operateUserId = Number(res.data[0].userId) 
        }  
    })
    boxInfo()
})

const handleAdd = () => {  // 点击添加业务员/操作员/业务编号 信息
    if(allocation.value.length >= 5) return ElMessage.warning('最多添加5组业务员/操作员/业务编号')
    let itemInfo = {
        businessUserId: '',           // 业务员id
        businessUserName: "",  // 业务员名称
        operateUserId: '',            // 操作员id
        operateUserName: "",   // 操作员名称
        businessNo: ""   // 业务编号
    }
    allocation.value.push(itemInfo)

} 
const handleDelete = (sub:number) => {  // 点击删除业务员/操作员/业务编号 信息
    if(allocation.value.length <= 1) return ElMessage.warning('至少保留一组业务员/操作员/业务编号')
    allocation.value.splice(sub,1)
} 


const handleSubmit = async() => {  // 提交订单
    const hasDuplicates = new Set(tableInfo.value.map(item => item.returnCityId)).size !== tableInfo.value.length;
    if(hasDuplicates) return ElMessage.warning("还箱城市存在重复，请检查添加数据")
    let quantityNo0 = false 
    tableInfo.value.forEach(item => {
        if(Number(item.boxQuantity) < 1){
            quantityNo0 = true 
        }
    })

    if(quantityNo0) return ElMessage.warning("预还箱量必须大于0！")
    if(!radioVal.value) return ElMessage.warning('请先阅读《集装箱租赁业务规则》、《用户服务协议和管理规则》并同意全部条款')
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
   
    const cityPriceList: Array<{
        returnCityId: number | string;
        unitPrice: string;
        currency: string;
        boxQuantity: number | string;
    }> = []
    if(tableInfo.value){
        tableInfo.value.forEach(item=>{ 
            const data = {
                returnCityId: item.returnCityId,
                unitPrice: item.unitPrice,
                currency: item.currency,
                boxQuantity: item.boxQuantity
            }

            cityPriceList.push(data)
        }) 
    }
    let reqInfo = {
        releaseRentId: rowData.value.id,
        boxType: param.boxType,
        boxCondition: param.boxCondition,
        // boxQuantity: param.inventory,
        planPickupDate: param.planPickupDate,
        paymentMethod: param.paymentMethod,
        contacts: rowData.value.publisherName,
        boxUsagePeriod:rowData.value.boxUsagePeriod,
        // unitPrice: param.unitPrice,
        // currency:param.currency,
        tel: rowData.value.publisherTel,
        period: param.period,
        areaCode:rowData.value.areaCode,
        leaveMsg: String(param.leaveMsg),
        allocation:  checkAllocation(allocation.value),
        agentDirection:agentDirection.value,
        cityPriceList: cityPriceList
    }
    if(reqInfo.allocation){
        let allocationInfo:any = []
        try{ 
            allocationInfo = JSON.parse(reqInfo.allocation)
        } catch(e) {
            allocationInfo = reqInfo.allocation
        }

        if(!allocationInfo[0].businessNo || !allocationInfo[0].operateUserId || !allocationInfo[0].businessUserId){
            loading.close()
            return ElMessage.error('请完善业务员/操作员/业务编号')
        } 
   
    }else{
        loading.close()
        return ElMessage.error('请完善业务员/操作员/业务编号')
    }
    await agentAddOrder(reqInfo).then((res:any)=>{ 
        if(res.code == "00000"){
            loading.close()
            router.push({
                path: '/orderManageHD/rentOrder',
                query: { 
                    status: '2'
                }
            });
        }else{
            loading.close()
            ElMessage.error(res.msg)
        }  
    }).catch((error:any)=>{ 
        loading.close()
        ElMessage.error(error.msg)
    }).finally(()=>{
        loading.close()
    })

}

const checkAllocation = (allocation: any) => {
    try {
        allocation = JSON.parse(allocation)
    } catch (e) {
        allocation = allocation 
    }
    allocation.forEach((item) => { 
        param.userSimpleList.forEach(item1 => {
            if(item1.userId == item.businessUserId){
                item.businessUserName = item1.nickname
            }
            if(item1.userId == item.operateUserId){
                item.operateUserName = item1.nickname
            }
        })
    })
    return JSON.stringify(allocation) || allocation
}

const handleInput = (value) => {
  // 使用正则表达式限制输入
  const reg = /^\d{0,7}(\.\d{0,2})?$/
  if (!reg.test(value)) {
    // 如果不符合规则，则回退到上一次有效值
    param.unitPrice = param.unitPrice.slice(0, -1)
    total.value = param.unitPrice * param.inventory
  }else {
    total.value = param.unitPrice * param.inventory
  }
}

const handleChange = () => { 
    const unitPrice = Number(param.unitPrice) || 0
    const inventory = Number(param.inventory) || 0
    total.value = Number((unitPrice * inventory).toFixed(2))
}

const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
};
const handlePeriodInput = (value) => {
  // 移除非数字字符
  let filtered = value.replace(/[^\d]/g, '');
    
    // 如果为空，设置为空字符串
    if (filtered === '') {
        param.period = '';
      return;
    }
    
    // 转换为数字
    const num = parseInt(filtered, 10);
    
    // 确保是有效的非负数
    if (!isNaN(num) && num >= 0) {
        param.period = num.toString();
    } else {
        param.period = '';
    }
}


// 功能函数 
// 
//  查找重复属性值及其对应的所有下标
//  @param array 目标数组
//  @param property 要检查的属性
//  @returns 包含重复值和对应下标的Map
//  */
function findDuplicateIndexes<T>(
  array: T[], 
  property: keyof T
): Map<any, number[]> {
  const valueToIndexes = new Map<any, number[]>();
  
  array.forEach((item, index) => {
    const value = item[property];
    
    if (!valueToIndexes.has(value)) {
      valueToIndexes.set(value, [index]);
    } else {
      valueToIndexes.get(value)!.push(index);
    }
  });
  
  // 过滤出有重复的值
  let repeatedSubscripts:any
  // 遍历Map中的每个键值对
    for (const [key, value] of valueToIndexes) {
        // 遍历数组值
        // value.forEach((item, index) => {
        //     console.log(`  - 数组索引 ${index}: ${item}`);
        // });
        if(value.length > 1){
            repeatedSubscripts = value
        }
    }
  
//   const duplicates = new Map<any, number[]>();
//   for (const [value, indexes] of valueToIndexes) {
//     if (indexes.length > 1) {
//       duplicates.set(value, indexes);
//     }
//   }
    
  
  return repeatedSubscripts || [];
}

// 限制输入数值格式
const formatterNumber = (value:any) =>{ 
  const val = value.replace(/[^\d.]/g, '').replace(/(\.\d*)\./g, '$1').replace(/^(\d{5})\d+/, '$1').replace(/\.(\d{2})\d+/, '.$1')
  if (val.indexOf('.') === -1) {
    return (val- 0)
  }else {
    const valArr = val.split('.')
    return (valArr[0] - 0).toString() + '.' + valArr[1]
  }
}
// 滚动到底部的方法
const scrollToBottom = () => {
    // 确保表格引用存在
    if (myTable.value) {
    // 获取表格内部的滚动容器
    const scrollWrapper = myTable.value.$el.querySelector('.el-scrollbar__wrap');
    if (scrollWrapper) {
        // 滚动到最底部
        scrollWrapper.scrollTop = scrollWrapper.scrollHeight;
        
        // 另一种确保滚动到底部的方法，判断当前是否接近底部
        // const { clientHeight, scrollHeight } = scrollWrapper;
        // if (scrollHeight - clientHeight - scrollWrapper.scrollTop > 1) {
        //   scrollWrapper.scrollTop = scrollWrapper.scrollHeight;
        // }
    }
    }
};
</script>
<style lang="scss" scoped>
.city-title{
    font-weight: 500;
    font-size: 18px;
}
.city-content{
    color: #999;
}
.input-with-select{
    color: #ff0000;
}
.total{
    color: #ff0000;
    font-size: 24px;
    font-weight: 600;
}
.el-price {
    :deep(.el-select__wrapper) {
        box-shadow: none !important;
    }

}
.el-table :deep(tr.warning-row) > td:nth-last-child(2) {
    border: 1px solid red !important;
}
</style>